﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web.Script;
using System.Net;
using System.Net.Sockets;
using System.Text;

[System.Web.Script.Services.ScriptService]
public class WebServicesPage : SessionPageBase
{
	[WebMethod, ScriptMethod]
	public static string[] getDataSocket(string text)
	{
		try
		{
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);

            return new string[] { "Waiting for a client..." };

            Socket client = newsock.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            //Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

            string welcome = "Welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);

            while (true)
            {
                data = new byte[1024];
                recv = client.Receive(data);
                if (recv == 0)
                    break;

                return new string[] { Encoding.ASCII.GetString(data, 0, recv) };
                //Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                client.Send(data, recv, SocketFlags.None);
            }
            
            //Console.WriteLine("Disconnected from {0}",clientep.Address);
            client.Close();
            newsock.Close();
		}
		catch (Exception)
		{
            return null;
		}
	}
}

